﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.DynamicApiController;

namespace Abc.Application.ApiAdminServices;

/// <summary>
/// 邮件发送模板
/// </summary>
[ApiDescriptionSettings("Api", Name = "EmailSendTemplate")]
[MaApi(  controller: "EmailSendTemplate", controllerDescription: "邮件发送模板", PCode = "API")]
[IgnoreAntiforgeryToken]
public class ApiEmailSendTemplateService : IDynamicApiController
{
    private readonly ILogger<ApiEmailSendTemplateService> _logger;
    private readonly ISqlSugarClient _db;

    public ApiEmailSendTemplateService(ILogger<ApiEmailSendTemplateService> logger
     , ISqlSugarClient db = null)
    {
        _logger = logger;
        _db = db;
    }

    /// <summary>
    /// 新增或更新一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [MaPermission(name: "新增或更新一条", actions: "Insert")]
    public async Task<long> Insert(ApiEmailSendTemplateInput input)
    {
        ////验证 父级下 唯一 Key是否存在
        //var isexit = await _db.Queryable<SysEmailSendTemplate>().AnyAsync(o => o.PKey == input.PKey && o.Key == input.Key);
        //if (isexit)
        //{
        //    throw Oops.Bah("唯一标识Key不能重复");
        //}
        var addentity = input.Adapt<SysEmailSendTemplate>();
        return await _db.InsertRsIdAsync(addentity);
    }

    /// <summary>
    /// 更新一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [MaPermission(name: "更新一条", actions: "Update")]
    public async Task<bool> Update(ApiEmailSendTemplateInput input)
    {
        ////验证 父级下 唯一 Key是否存在
        //var isexit = await _db.Queryable<SysEmailSendTemplate>().AnyAsync(o => o.PKey == input.PKey && o.Key == input.Key && o.Id != input.Id);
        //if (isexit)
        //{
        //    throw Oops.Bah("唯一标识Key不能重复");
        //}
        var dbentity = await _db.Queryable<SysEmailSendTemplate>().FirstAsync(o => o.Id == input.Id.Value);
        input.Adapt(dbentity);
        return await _db.UpdateAsync(dbentity);
    }

    /// <summary>
    /// 删除一条
    /// </summary>
    /// <param name="id"></param>
    [MaPermission(name: "删除一条", actions: "Delete")]
    public async Task<bool> Delete(long id)
    {
        if (id <= 0) throw Oops.Bah("id不能为0");
        return await _db.DeleteByIdAsync<SysEmailSendTemplate>(id);
    }

    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="ids">需要删除的数据，多条以英文逗号隔开</param>
    [MaPermission(name: "批量删除", actions: "BatchDelete")]
    public async Task<bool> BatchDelete(string ids)
    {
        return await _db.DeleteByIdsAsync<SysEmailSendTemplate>(ids);
    }

    /// <summary>
    /// 查询一条
    /// </summary>
    /// <param name="id"></param>
    [MaPermission(name: "查询一条", actions: "Get")]
    public async Task<ApiEmailSendTemplateOut> Get(long id)
    {
        return await _db.GetByIdAsync<SysEmailSendTemplate, ApiEmailSendTemplateOut>(id);
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="searchQuery"></param>
    /// <returns></returns>
    [MaPermission(name: "分页查询", actions: "GetAllByPage")]
    public async Task<PagedList<ApiEmailSendTemplateOut>> GetAllByPageToLayui(ApiEmailSendTemplateQuery searchQuery)
    {
        var queryable = _db.Queryable<SysEmailSendTemplate>();

        #region 筛选条件

        ////开始日期
        //if (searchQuery.StartDate.HasValue)
        //{
        //    queryable = queryable.Where(o => o.CreationTime >= searchQuery.StartDate.Value);
        //}
        ////结束日期
        //if (searchQuery.EndDate.HasValue)
        //{
        //    var endtime = Convert.ToDateTime($"{searchQuery.EndDate.Value:yyyy-MM-dd} 23:59:59");
        //    queryable = queryable.Where(o => o.CreationTime <= endtime);
        //}
        ////关键词
        //if (string.IsNullOrWhiteSpace(searchQuery.KeyWords))
        //{
        //    var kw = searchQuery.KeyWords?.Trim()?.ToLower()??"";
        //    queryable = queryable.Where(o=>o.Title.Contains(kw));
        //}

        #endregion 筛选条件

        //queryable = queryable.OrderByDescending(o => o.Id);
        var pagelist = await queryable.Select(a => new ApiEmailSendTemplateOut()
        {
            Id = a.Id.SelectAll(),
            #region 自定义
            IsEnableName = a.IsEnable ? "是" : "否",// 
            //IsDeletedName =  a.IsDeleted?"是":"否"  ,// 
            TemplateTypeName = a.TemplateType.ToString(),
            IsVerCodeName = a.IsVerCode ? "是" : "否",//是否验证码
            #endregion
        })
        .Mapper(src =>
        {
        })
        .ToPagedListAsync(searchQuery.Page, searchQuery.Limit);

        //pagelist= await pageResult.ToPagedListAsync<SysEmailsendtemplate, ApiEmailsendtemplateOut>(searchQuery.Page, searchQuery.Limit);
        return pagelist;
    }

    /// <summary>
    /// 设置状态
    /// </summary>
    /// <param name="id"></param>
    /// <param name="state"></param>
    /// <param name="field">字段名</param>
    /// <returns></returns>
    [MaPermission(name: "设置状态", actions: "SetState")]
    public async Task<bool> SetState(long id, bool state, string field)
    {
        return await _db.SetStateByIdAsync<SysEmailSendTemplate>(id, state, field);
    }

    #region 冗余方法

    /// <summary>
    /// 查询所有
    /// </summary>
    /// <returns></returns>
    [MaPermission(name: "查询所有", actions: "GetAll")]
    public async Task<List<ApiEmailSendTemplateOut>> GetAll()
    {
        return await _db.GetListAsync<SysEmailSendTemplate, ApiEmailSendTemplateOut>();
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="searchQuery"></param>
    /// <returns></returns>
    public async Task<PagedList<ApiEmailSendTemplateOut>> GetAllByPage(ApiEmailSendTemplateQuery searchQuery)
    {
        var queryable = _db.Queryable<SysEmailSendTemplate>();

        #region 筛选条件

        ////开始日期
        //if (searchQuery.StartDate.HasValue)
        //{
        //    queryable = queryable.Where(o => o.CreationTime >= searchQuery.StartDate.Value);
        //}
        ////结束日期
        //if (searchQuery.EndDate.HasValue)
        //{
        //    var endtime = Convert.ToDateTime($"{searchQuery.EndDate.Value:yyyy-MM-dd} 23:59:59");
        //    queryable = queryable.Where(o => o.CreationTime <= endtime);
        //}
        ////关键词
        //if (string.IsNullOrWhiteSpace(searchQuery.KeyWords))
        //{
        //    var kw = searchQuery.KeyWords?.Trim()?.ToLower() ?? "";
        //    queryable = queryable.Where(o => o.Title.Contains(kw));
        //}

        #endregion 筛选条件

        queryable = queryable.OrderByDescending(o => o.Id);
        var pagelist = await queryable.Select(a => new ApiEmailSendTemplateOut()
        {
            Id = a.Id.SelectAll(),
            #region 自定义
            IsEnableName = a.IsEnable ? "是" : "否",// 
            //IsDeletedName =  a.IsDeleted?"是":"否"  ,// 
            TemplateTypeName = a.TemplateType.ToString(),
            IsVerCodeName = a.IsVerCode ? "是" : "否",//是否验证码
            #endregion
        })
        .Mapper(src =>
        {
        })
        .ToPagedListAsync(searchQuery.Page, searchQuery.Limit);



        //var pagelist= await pageResult.ToPagedListAsync<SysEmailsendtemplate, ApiEmailsendtemplateOut>(searchQuery.Page, searchQuery.Limit);

        return pagelist;
    }

    /// <summary>
    /// 假删除
    /// </summary>
    /// <param name="id"></param>
    public async Task<bool> FakeDelete(long id)
    {
        return await _db.FakeDeleteAsync<SysEmailSendTemplate>($"{id}");
    }

    /// <summary>
    /// 批量假删除
    /// </summary>
    /// <param name="ids">需要删除的数据，多条以英文逗号隔开</param>
    public async Task<bool> BatchFakeDelete(string ids)
    {
        return await _db.FakeDeleteAsync<SysEmailSendTemplate>(ids);
    }

    #endregion 冗余方法

}